package cn.blue.system.service.impl;

import cn.blue.system.domain.Menu;
import cn.blue.system.service.IMenuService;
import cn.blue.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hui
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    /**
     *
     * @return查询上级菜单
     */
    @Override
    public List<Menu> first() {

        List<Menu> all = super.findAll();
        //流的方式把paerntId为空的过滤出来
        return all.stream().filter(al->null == al.getParentId()).collect(Collectors.toList());
    }


    /**
     * 菜单树
     * @return
     */
    @Override
    public List<Menu> tree() {
        ArrayList<Menu> result = new ArrayList<>();
        List<Menu> menus = super.findAll();
        Map<Long, Menu> menusMap = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e));
        menus.forEach(menu -> {
            if(null == menu.getParentId()){
                result.add(menu);
            }else {
                Menu parent = menusMap.get(menu.getParentId());
                if (null == parent){
                    return;
                }
                parent.getChildren().add(menu);
            }
        });
        return result;
    }
}
